CROSS = riscv64-unknown-elf
CC = $(CROSS)-gcc
OBJDUMP = $(CROSS)-objdump
NM = $(CROSS)-nm

CFLAGS = -march=rv64gc -mabi=lp64 -mcmodel=medany -ffreestanding -nostdlib -O0 -g
SRCS = entry.S main.c uart.c console.c printf.c kalloc.c vm.c string.c
OBJS = entry.o main.o uart.o console.o printf.o kalloc.o vm.o string.o

all: kernel.elf

entry.o: entry.S
	$(CC) $(CFLAGS) -c entry.S -o entry.o

main.o: main.c
	$(CC) $(CFLAGS) -c main.c -o main.o

uart.o: uart.c uart.h
	$(CC) $(CFLAGS) -c uart.c -o uart.o

console.o: console.c console.h uart.h
	$(CC) $(CFLAGS) -c console.c -o console.o

printf.o: printf.c printf.h console.h
	$(CC) $(CFLAGS) -c printf.c -o printf.o

string.o: string.c string.h types.h
	$(CC) $(CFLAGS) -c string.c -o string.o

kalloc.o: kalloc.c kalloc.h types.h string.h
	$(CC) $(CFLAGS) -c kalloc.c -o kalloc.o

vm.o: vm.c vm.h kalloc.h types.h string.h
	$(CC) $(CFLAGS) -c vm.c -o vm.o

kernel.elf: $(OBJS) kernel.ld
	$(CC) $(CFLAGS) -T kernel.ld -Wl,-Map=kernel.map -o kernel.elf $(OBJS)

clean:
	rm -f *.o kernel.elf kernel.map

run: kernel.elf
	qemu-system-riscv64 -machine virt -nographic -bios none -kernel kernel.elf

gdb-run: kernel.elf
	qemu-system-riscv64 -machine virt -nographic -bios none -kernel kernel.elf -s -S
